package com.lottery.ruok.lottrey.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewStub;
import android.widget.ListView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.AccountDetailAdapter;
import com.lottery.ruok.lottrey.dialog.FiltrateDialog;
import com.lottery.ruok.lottrey.eventbusObject.FilterGetLogs;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetCashLogRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetCashLogResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;

import ui.NavigateBar;
import utils.LogUtil;
/*
 * 账户明细
 * */

public class AccountDetailActivity extends BaseActivity {

    @BindView(R.id.navigateBar)
    NavigateBar navigateBar;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private AccountDetailAdapter myAdapter;
    private int mPage = 0;
    private String filterStartTime;
    private String filterEndTime;
    private String filterTypes;
    private View emptyLayout;

    private boolean isInitData = true;
    private final int pageNum = 20;

    private void setEmtpyView() {
        if (emptyLayout == null) {
            ViewStub stub = findViewById(R.id.no_net_viewstub);
            View view = stub.inflate();
            emptyLayout = view.findViewById(R.id.no_net_view);
            emptyLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getList(filterStartTime, filterEndTime, filterTypes, 0);
                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_detail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void startFilter(FilterGetLogs filterGetLogs) {
        mPage = 0;
        filterStartTime = filterGetLogs.getStart_time();
        filterEndTime = filterGetLogs.getEnd_time();
        filterTypes = filterGetLogs.getTypes();
        getList(filterGetLogs.getStart_time(), filterGetLogs.getEnd_time(), filterGetLogs.getTypes(), mPage);
    }

    private void getList(String time_start, String time_end, String types, final int page) {
        RetrofitBase.getRetrofit().create(GetCashLogRequest.class).getResult(UserInfo.getToken(), time_start, time_end, types, page * 20, pageNum)
                .compose(RxHelper.<GetCashLogResponse>handleResult())
                .subscribe(new RxSubscribe<GetCashLogResponse>(this) {
                    @Override
                    protected void _onNext(GetCashLogResponse getCashLogResponse) {
                        if(getCashLogResponse.getList() != null && getCashLogResponse.getList().size() < pageNum){
                            mRefreshLayout.setEnableLoadMore(false);
                        }else{
                            mRefreshLayout.setEnableLoadMore(true);
                        }
                        if (myAdapter == null) {//第一次进入
                            myAdapter = new AccountDetailAdapter(getCashLogResponse, AccountDetailActivity.this);
                            listview.setAdapter(myAdapter);
                        } else {//非第一次进入
                            if (page == 0) {//when pull down list
                                myAdapter.setDatas(getCashLogResponse);
                                mRefreshLayout.finishRefresh();
                            } else {//when pull up list
                                myAdapter.getDatas().getList().addAll(getCashLogResponse.getList());
                                mRefreshLayout.finishLoadMore();
                            }
                            myAdapter.notifyDataSetChanged();
                        }

                        mPage = page;

                        if (myAdapter.getDatas().getList().size() == 0) {
                            setEmtpyView();
                        } else {
                            if (emptyLayout != null) {
                                emptyLayout.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                        if (page == 0) {
                            mRefreshLayout.finishRefresh();
                        } else {
                            mRefreshLayout.finishLoadMore();
                        }

                        if (myAdapter == null || myAdapter.getDatas() == null || myAdapter.getDatas().getList().size() == 0) {
                            setEmtpyView();
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        if(isInitData){
                            return true;
                        }
                        return false;
                    }
                });
    }

    private void init() {
        isInitData = true;
        getList(null, null, null, mPage);

        navigateBar.setOnOperateClickListener(new NavigateBar.OnOperateClickListener() {
            @Override
            public void onOperateClick(View view) {
                FiltrateDialog filtrateDialog = new FiltrateDialog();
                LogUtil.d("你为啥不出来");
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                bundle.putString("types", filterTypes);
                bundle.putString("startTime",filterStartTime);
                bundle.putString("endTime",filterEndTime);
                filtrateDialog.setArguments(bundle);
                FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
                fts.setCustomAnimations(R.anim.anim_enter_from_bottom, R.anim.anim_exit_from_bottom, R.anim.anim_enter_from_bottom, R.anim.anim_exit_from_bottom);
                fts.replace(android.R.id.content, filtrateDialog);
                fts.addToBackStack("account");
                fts.commitAllowingStateLoss();
            }
        });

       /* // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, true);
        // 设置下拉刷新和上拉加载更多的风格
        swipeRefreshLayout.setRefreshViewHolder(refreshViewHolder);

        swipeRefreshLayout.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                getList(filterStartTime, filterEndTime, filterTypes, mPage + 1);
                return true;
            }

            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                mPage = 0;
                getList(filterStartTime, filterEndTime, filterTypes, mPage);
            }
        });*/

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mRefreshLayout.setEnableRefresh(true);//启用刷新
                mPage = 0;
                isInitData = false;
                getList(filterStartTime, filterEndTime, filterTypes, mPage);

            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mRefreshLayout.setEnableLoadMore(true);//启用加载
                isInitData = false;
                getList(filterStartTime, filterEndTime, filterTypes, mPage + 1);
            }
        });

    }
}